<template>
  <div>
    <!--搜索表单-->
    <el-form :inline="true" class="demo-form-inline">

      <el-form-item label="课程名称:">
        <el-input v-model="selectSubject.subjectName" placeholder="课程名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="课程编号:">
        <el-input v-model="selectSubject.subjectNumber" placeholder="课程编号" clearable></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

      <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
      <el-button type="primary" plain @click="dialogVisible = true;selectTeacher()">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
        title="编辑信息"
        :visible.sync="dialogVisible"
        width="30%"
        @close='closeDialog'
    >

      <el-form ref="subject" :model="subject" label-width="80px" :rules="rules">

        <el-form-item label="课程名称" prop="subjectName">
          <el-input v-model="subject.subjectName"></el-input>
        </el-form-item>

        <el-form-item label="课程编号" prop="subjectNumber">
          <el-input v-model="subject.subjectNumber"></el-input>
        </el-form-item>

        <el-form-item label="课程学分" prop="subjectCredit">
          <el-input v-model="subject.subjectCredit"></el-input>
        </el-form-item>

        <el-form-item label="授课教师">
          <el-select v-model="subject.teacherName" clearable placeholder="请选择" @change="(val) => checkChange(val)">
            <el-option
                v-for="item in options1"
                :key="item.teacherName"
                :label="item.teacherName"
                :value="item.teacherName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addSubject">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


    <!--  修改学生信息-->
    <!--添加数据对话框表单-->
    <el-dialog
        title="编辑信息"
        :visible.sync="dialogVisible1"
        width="30%"
        @close='closeDialog'
    >
      <el-form ref="subject" :model="subject" label-width="80px" :rules="rules">

        <el-form-item label="课程名称" prop="subjectName">
          <el-input v-model="subject.subjectName"></el-input>
        </el-form-item>

        <el-form-item label="课程编号" prop="subjectNumber">
          <el-input v-model="subject.subjectNumber"></el-input>
        </el-form-item>

        <el-form-item label="课程学分" prop="subjectCredit">
          <el-input v-model="subject.subjectCredit"></el-input>
        </el-form-item>

        <el-form-item label="授课教师">
          <el-select v-model="subject.teacherName" clearable placeholder="请选择" @change="(val) => checkChange(val)">
            <el-option
                v-for="item in options1"
                :key="item.teacherName"
                :label="item.teacherName"
                :value="item.teacherName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="update">提交</el-button>
          <el-button @click="dialogVisible1 = false;flushed()">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


    <!--表格-->
    <template>
      <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            label="序号"
            type="index"
            align="center"
            width="50">
        </el-table-column>

        <el-table-column
            prop="subjectNumber"
            label="课程编号"
            align="center"
        >
        </el-table-column>

        <el-table-column
            prop="subjectName"
            label="课程名称"
            align="center"
        >
        </el-table-column>

        <el-table-column
            prop="subjectCredit"
            align="center"
            label="课程学分">
        </el-table-column>

        <el-table-column
            prop="teacherName"
            align="center"
            label="教师姓名">
        </el-table-column>

        <el-table-column
            align="center"
            label="操作">

          <el-row slot-scope="scope">
            <el-button type="primary" @click="dialogVisible1 = true;pageEcho(scope.row);selectTeacher()">修改</el-button>
            <el-button type="danger" @click="dele(scope.row)">删除</el-button>
          </el-row>

        </el-table-column>

      </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
    </el-pagination>

  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "SubjectPage",
  data() {
    // 自定义校验课程名称js逻辑
    var subjectName = /^[a-z0-9A-Z\u4e00-\u9fa5]+$/
    var validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空!!'))
      }
      setTimeout(() => {
        if (!subjectName.test(value)) {
          callback(new Error('格式有误,请输入正确格式'))
        } else {
          callback()
        }
      }, 100)
    }

    //自定义校验课程编号
    var subjectNumber = /^\d{3}$/
    var validateNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空!!'))
      }
      setTimeout(() => {
        if (!subjectNumber.test(value)) {
          callback(new Error('格式有误,请输入3位的课程编号'))
        } else {
          callback()
        }
      }, 100)
    }
    //自定义校验学分
    var subjectCredit = /^((0\.[1-9]{1})|(([1-9]{1})(\.\d{1})?))$/
    var validateCredit = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空!!'))
      }
      setTimeout(() => {
        if (!subjectCredit.test(value)) {
          callback(new Error('格式有误,请输入10位的学号'))
        } else {
          callback()
        }
      }, 100)
    }
    return {
      // 当前页码
      currentPage: 1,
      //当前页显示条数
      pageSize: 5,
      //总条数
      totalCount: 0,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 修改数据对话框是否展示标记
      dialogVisible1: false,
      // 成绩模型数据
      subject: {
        subjectName: '',
        subjectNumber: '',
        teacherName: '',
        teacherNumber: '',
        subjectCredit: '',
        subjectId: '',
      },
      //查询的数据
      selectSubject: {
        subjectName: '',
        subjectNumber: '',
      },
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      //新增中的选框数据
      options: [],
      //学生学号
      row: [],
      //被选中的ids
      selectedIds: [],
      //选框
      options1: [],
      // 校验规则
      rules: {
        // 校验科目，主要通过validator来指定验证器名称
        subjectName: [{required: true, validator: validateName, trigger: 'blur'}],
        subjectNumber: [{required: true, validator: validateNumber, trigger: 'blur'}],
        subjectCredit: [{required: true, validator: validateCredit, trigger: 'blur'}],
      },
    }
  },
  mounted: function () {
    this.page();
  },
  methods: {
    //刷新页面
    flushed() {
      location.reload();
    },

    //分页查询
    page() {
      var that = this;
      this.$http.post('/subject/selectByPage/' + this.currentPage + '/' + this.pageSize, this.selectSubject)
          .then(function (response) {
            // console.log(response)
            if (response.data.code == '200') {
              that.tableData = response.data.data.rows;
              // console.log(that.tableData);
              that.totalCount = response.data.data.totalCount;
            } else {
              that.$message.error("服务器错误，请稍后！")
            }
          }).catch(function (error) {
        console.log(error);
      })
    },

    /*删除数据*/
    dele(row) {
      var that = this;
      // console.log(row.subjectId);
      this.$confirm('此操作将永久删除此数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/subject/deleteById/" + row.subjectId)
            .then(function (response) {
              // console.log(response)
              if (response.data.code == '200') {
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新页面
                location.reload();
              } else {
                that.$message.error("删除失败，请重试！");
                location.reload();
              }
            }).catch(function (error) {
          console.log(error);
          that.$message.error("服务器错误，请重试！");
        })
      }).catch(() => {
        that.$message({
          type: 'info',
          message: '已取消删除'
        });
        location.reload();
      });
    },

    /*批量删除*/
    deleteByIds() {
      var that = this;
      //获取当前复选框的数据
      // console.log(this.multipleSelection);
      //1.创建id数组【】，从this.multipleSelection中获取
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let selectionElement = this.multipleSelection[i];
        this.selectedIds[i] = selectionElement.subjectId;
      }
      // console.log(that.selectedIds);
      that.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        //2.发送axios请求
        this.$http.delete("/subject/deleteByIds", {data: that.selectedIds})
            .then(function (response) {
              // console.log(response.data);
              if (response.data.code == '200') {
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                location.reload();
              } else {
                that.$message.error(response.data.msg)
                location.reload();
              }
            }).catch(function (error) {
          console.log(error);
        });
      }).catch(() => {
        that.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    /* 关闭新建清空表单 */
    closeDialog() {
      this.flushed();
    },

    //获取新增选框中的数据
    checkChange(val){
      var that=this;
      // console.log(val);
      for (let item of that.options1) {
        // console.log(item);
        if (item.teacherName==val){
          // console.log(item.teacherNumber);
          that.subject.teacherNumber=item.teacherNumber;
        }
      }
    },

    //页面回显
    pageEcho(row) {
      // console.log(row);
      this.subject = row;
    },

    //修改表格中发的数据
    update() {
      // console.log(this.subject);
      var that = this;
      this.$refs.subject.validate((status) => {
        if (status) {
          // true 表示通过验证
          // 进行相关数据的请求
          this.$confirm('此操作将永久修改该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.$http.put("/subject/updateById", this.subject)
                .then(function (response) {
                  // console.log(response);
                  // debugger;
                  if (response.data.code == '200') {
                    that.dialogVisible1 = false;
                    that.flushed();
                    that.$message({
                      type: 'success',
                      message: '修改成功!'
                    });
                  } else {
                    that.$message.error("服务器错误，请重试！");
                    that.flushed();
                  }
                }).catch(function (error) {
              console.log(error);
            })
          }).catch(() => {
            that.$message({
              type: 'info',
              message: '已取消修改！'
            });
          });
        } else {
          this.$message.error('格式错误,请重试！')
          that.closeDialog();
        }
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },

    // 查询方法
    onSubmit() {
      this.page();
    },

    // 添加数据
    addSubject() {
      // console.log(this.subject);
      var that = this;
      this.$refs.subject.validate((status) => {
        if (status) {
          this.$http.post("/subject/addSubject", that.subject)
              .then(function (response) {
                // console.log(response.data.code);
                if (response.data.code == '200') {
                  that.$message.success("添加成功！");
                  that.dialogVisible = false;
                  location.reload();
                } else {
                  that.$message.error(response.data.msg);
                  location.reload();
                }
              }).catch(function (error) {
            console.log(error);
          })
        } else {
          this.$message.error('格式错误,请重试！')
          that.closeDialog();
        }
      })
    },

    //新增的复选框内容
    selectTeacher() {
      var that=this;
      this.$http.get('/teacher/selectTeacher')
          .then(function (response){
            // console.log(response.data.data);
            that.options1=response.data.data;
            // console.log(that.options1)
          }).catch(function (error){
            console.log(error);
      })
    },

    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.page();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      // console.log(this.currentPage)
      this.page();
    },

    //隔行变色
    tableRowClassName({rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    }

  }
}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>